package org.example.leetCode;

/**
 * @author Administrator
 */
public class SpiralOrder {
    public static void main(String[] args) {
        int[][] temp = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        SpiralOrder spiralOrder = new SpiralOrder();
        int[] ints = spiralOrder.spiralOrder(temp);
    }

    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return new int[0];
        }else if (matrix.length==1){
            return matrix[0];
        }
        boolean[][] visited = new boolean[matrix.length][matrix[0].length];
        int[] result = new int[matrix.length * matrix[0].length];
        return circle(matrix, 0, 0, visited, result, 0);

    }

    private int[] circle(int[][] matrix, int m, int n, boolean[][] visited, int[] result, int i) {
        if (n<0||m<0||m >= matrix.length||n >= matrix[0].length||visited[m][n]) {
            return result;
        }
        while (n < matrix[0].length && !visited[m][n]) {
            result[i++] = matrix[m][n];
            visited[m][n++] = true;
        }
        n--;
        m++;
        while (m < matrix.length && !visited[m][n]) {
            result[i++] = matrix[m][n];
            visited[m++][n] = true;
        }
        m--;
        n--;
        while (n >= 0 && !visited[m][n]) {
            result[i++] = matrix[m][n];
            visited[m][n--] = true;
        }
        m--;
        n++;
        while (m >= 0 && !visited[m][n]) {
            result[i++] = matrix[m][n];
            visited[m--][n] = true;
        }
        m++;
        n++;
        return circle(matrix, m, n, visited, result, i);
    }
}
